/**
* @program: Go
*
* @description:消息未送达表
*
* @author: Mr.chen
*
* @create: 2020-12-01 10:21
**/
package models

import (
	"ydd-im/service/api/tools/util"
	mydb "ydd-im/service/dbproxy/util/mysql/conn"
	"database/sql"
	"errors"
	"fmt"
	"strings"
	"time"
)

type MessageArrive struct {
	Id         int       `db:"id" json:"id"`                 //消息ID
	MessageId  int       `db:"messageId" json:"messageId"`   //消息ID
	Dstid      int       `db:"dstid" json:"dstid"`           //目标ID
	Createtime time.Time `db:"createtime" json:"createtime"` // 创建时间
	State      int       `db:"state" json:"state"`           //目标ID
}

//orm 回调
func (ma *MessageArrive) TableName() string {
	return TNMessageArrive()
}

func NewMessageArrive() *MessageArrive {
	return &MessageArrive{}
}

// 添加消息
func (ma *MessageArrive) AddMessageArrive(messageArrive *MessageArrive) (insertid int64, err error) {
	sqlStr := "insert  into " + ma.TableName() + "(messageId,dstid,createtime) values (?,?,?)"
	dbconn,err := mydb.DBConn("w")
	if err != nil {
		return 0, err
	}
	ret, err := dbconn.Exec(sqlStr, messageArrive.MessageId, messageArrive.Dstid, util.GetCurrentDateTime())
	if err != nil {
		return 0, err
	}

	theID, err := ret.LastInsertId() // 新插入数据的id
	if err != nil {
		return 0, err
	}
	return theID, nil
}

// BatchInsertMessageArrive 自行构造批量插入的语句 https://www.liwenzhou.com/posts/Go/sqlx_bulk_insert/
func (ma *MessageArrive) BatchInsertMessageArrive(messageArrive []*MessageArrive) (insertid int64, err error) {
	// 存放 (?, ?) 的slice
	valueStrings := make([]string, 0, len(messageArrive))
	// 存放values的slice
	valueArgs := make([]interface{}, 0, len(messageArrive)*2)
	// 遍历users准备相关数据
	for _, m := range messageArrive {
		// 此处占位符要与插入值的个数对应
		valueStrings = append(valueStrings, "(?, ?,?)")
		valueArgs = append(valueArgs, m.MessageId)
		valueArgs = append(valueArgs, m.Dstid)
		valueArgs = append(valueArgs, m.Createtime)
	}
	// 自行拼接要执行的具体语句
	sqlStr := fmt.Sprintf("INSERT INTO "+ma.TableName()+"(messageId,dstid,createtime) VALUES %s",
		strings.Join(valueStrings, ","))
	dbconn,err := mydb.DBConn("w")
	if err != nil {
		return 0, err
	}
	ret, err := dbconn.Exec(sqlStr, valueArgs...)
	if err != nil {
		return 0, err
	}
	theID, err := ret.LastInsertId() // 新插入数据的id
	if err != nil {
		return 0, err
	}
	return theID, nil

}

// 删除数据
func (ma *MessageArrive) DeleteRowMessageArrive(messageId int, dstid int) (err error) {
	sqlStr := "delete from " + ma.TableName() + " where messageId = ? and dstid = ? "
	dbconn,err := mydb.DBConn("w")
	if err != nil {
		return  err
	}
	ret, err := dbconn.Exec(sqlStr, messageId, dstid)
	if err != nil {
		return err
	}
	_, err = ret.RowsAffected() // 操作影响的行数
	if err != nil {
		return err
	}
	return nil
}

// 删除数据
func (ma *MessageArrive) UpdateRowMessageArrive(messageId int, dstid int, state int) (err error) {
	sqlStr := "update  " + ma.TableName() + " set state = ?  where messageId = ? and dstid = ? "
	dbconn,err := mydb.DBConn("w")
	if err != nil {
		return  err
	}
	ret, err := dbconn.Exec(sqlStr, state, messageId, dstid)
	if err != nil {
		return err
	}
	_, err = ret.RowsAffected() // 操作影响的行数
	if err != nil {
		return err
	}
	return nil
}

// 根据uid,client_type查询用户信息
func (ma *MessageArrive) GetMessageArriveJoinMessageList(userid int) (message []Message, err error) {
	message = []Message{}
	m := &Message{}
	u := &User{}
	sqlStr := "select b.id,b.userid,b.messageType,a.dstid,b.media,b.content,b.pic,b.url,b.createtime,c.username from " + ma.TableName() + " as a inner join " + m.TableName() + " as b on a.messageId = b.id inner join " + u.TableName() + " as c  on b.userid = c.id    where a.dstid = ? and a.state = 0 order by b.id asc"
	dbconn,err := mydb.DBConn("r")
	if err != nil {
		return message, err
	}
	err = dbconn.Select(&message, sqlStr, userid)
	if err == sql.ErrNoRows { // 为空
		return message, nil
	}
	if err != nil {
		return message, err
	}
	return message, nil
}

/**
 * 获取历史记录
 * @access  public
 * @param   []string     where     条件
 * @param   string     field   获取的列
 * @param   int     pageNumber   第几页，从1开始
 * @param   int     pageCount   每页的数量
 * @param   string     orderby   排序
 * @return  []slice group   群列表
 * @return  error  err  错误信息
 */
func (ma *MessageArrive) GetMessageHistoryLogList(where []string,field string,pageNumber,pageCount int,orderby string ) (message []Message, err error) {
	message = []Message{}
	m := &Message{}
	u := &User{}
	if len(field) == 0 {
		field = "b.id"
	}
	sqlStr := "select " + field + " from " + ma.TableName() + " as a inner join " + m.TableName() + " as b on a.messageId = b.id inner join " + u.TableName() + " as c  on b.userid = c.id  "
	if len(where) > 0 {
		whereStr := fmt.Sprintf(" WHERE %s", strings.Join(where, " AND "))
		isok := util.FilteredSQLInject(whereStr)
		if (isok) {
			return message, errors.New("参数有误，请重试！")
		}
		sqlStr += whereStr
	}
	if len(orderby) == 0 {
		sqlStr += " order by b.id asc"
	}else{
		sqlStr += " "+orderby
	}
	var firstlimit,endlimit int
	if pageCount > 0 {
		if pageNumber <=1 {
			pageNumber = 1
		}
		firstlimit = (pageNumber-1)*pageCount;;
		endlimit = pageCount;
		sqlStr += fmt.Sprintf(" limit %d,%d ",firstlimit,endlimit)
	}else{
		firstlimit = 0;
		endlimit = 0;
	}
	dbconn,err := mydb.DBConn("r")
	if err != nil {
		return message, err
	}
	err = dbconn.Select(&message, sqlStr)
	if err == sql.ErrNoRows { // 为空
		return message, nil
	}
	if err != nil {
		return message, err
	}
	return message, nil
}